package org.qtproject.example;

import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.Manifest;
import android.os.storage.StorageManager;
import android.os.storage.StorageVolume;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.app.PendingIntent;
import android.widget.Toast;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.location.LocationManager;
import android.location.Criteria;
import android.provider.Settings;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationProvider;
import java.lang.ClassLoader;
import dalvik.system.DexClassLoader;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.InputStream;
import java.io.OutputStream;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import java.io.File;

import android.provider.DocumentsContract;
import android.provider.MediaStore;

import java.lang.reflect.Method;
import jcifs.smb.SmbFile;
import jcifs.smb.NtlmPasswordAuthentication;
import jcifs.smb.SmbFileOutputStream;
import jcifs.smb.SmbFileInputStream;
import jcifs.smb.ACE;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.net.MalformedURLException;


public class ExtendsQtWithJava extends org.qtproject.qt5.android.bindings.QtActivity
{
    private static ExtendsQtWithJava m_instance;
    private static Context context;

    public ExtendsQtWithJava(){
        m_instance = this;
    }

    @Override
    public void onCreate(Bundle bd){
        context = getApplicationContext();
        super.onCreate(bd);
    }
    public static Context getContext(){
        return context;
    }


    // 安卓端文件夹路径获取
    public static String getFileList(String path){

        jcifs.Config.setProperty("jcifs.smb.client.responseTimeout", "5000");

        ExtendsQtNative.printInfo("getFileList:" + path);
        try{
            File folder = new File(path);
            if(!folder.exists()){
                folder = Environment.getExternalStorageDirectory();
            }

            File[] files = folder.listFiles();
            String res = "";
            for(File file : files){
                if(file.isFile()){
                    res += file.getName() + ",";
                }else{
                    res += file.getName() + "/,";
                }
            }
            return res;
        }catch(Exception e){
            return "PERMISSION_DENIED";
        }

    }

    // SMB文件夹路径获取
    public static String getFileList_SMB (String url, String path, String username, String password){

        NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(url, username, password);
        String url_path = "smb://" + url + "/" + path;

        String res = "";
        try{
            SmbFile file = new SmbFile(url_path, auth);
            if(!file.exists()){
                ExtendsQtNative.printInfo("输入路径不存在");
                return "PERMISSION_DENIED";
            }
            if (file.isFile()) {
                ExtendsQtNative.printInfo("输入路径不是文件夹");
                return "PERMISSION_DENIED";
            }
            if(file.isDirectory()){
                String[] list = file.list();
                for(int i = 0; i < list.length; i ++){
                    //res += list[i] + ",";
                    try{
                        SmbFile subfile = new SmbFile(url_path + "/" + list[i], auth);
                        if(subfile.isDirectory()){
                            res += list[i] + "/,";
                        }else{
                            res += list[i] + ",";
                        }
                    }catch(Exception e){
                        ExtendsQtNative.printInfo("出错");
                        return "PERMISSION_DENIED";
                    }
                }
            }
        }catch(Exception e){
            ExtendsQtNative.printInfo("出错");
            return "PERMISSION_DENIED";
        }
        return res;
    }

    // SMB下载文件 [TODO] 校验所选路径是否已经存在文件
    public static String downloadFile_SMB(String url, String remotePath, String username, String password, String localPath){    // 将SMB文件下载到本地
        NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(url, username, password);
        String url_path = "smb://" + url + "/" + remotePath;

        InputStream in = null;
        OutputStream out = null;
        try {
            SmbFile remoteFile = new SmbFile(url_path, auth);
            File localFile = new File(localPath);
            in = new BufferedInputStream(new SmbFileInputStream(remoteFile));
            out = new BufferedOutputStream(new FileOutputStream(localFile));
            byte[] buffer = new byte[1024];
            while (in.read(buffer) != -1) {
                out.write(buffer);
                buffer = new byte[1024];
            }
        } catch (Exception e) {
            return "PERMISSION_DENIED";
        } finally {
            try {
                out.close();
                in.close();
            } catch (IOException e) {
                return "PERMISSION_DENIED";
            }
        }
        return "SUCCESS";
    }

    // SMB上传文件
    public static String uploadFile_SMB(String url, String remotePath, String username, String password, String localPath){      // 将本地文件上传到SMB
        NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(url, username, password);
        String url_path = "smb://" + url + "/" + remotePath;

        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            File localFile = new File(localPath);
            inputStream = new FileInputStream(localFile);
            SmbFile smbFile = new SmbFile(url_path, auth);
            smbFile.connect();
            ExtendsQtNative.printInfo("上载路径："+url_path);
            outputStream = new SmbFileOutputStream(smbFile);
            byte[] buffer = new byte[4096];
            int len = 0;
            while ((len = inputStream.read(buffer, 0, buffer.length)) != -1) {
                outputStream.write(buffer, 0, len);
            }
            outputStream.flush();
        } catch (Exception e){
            return "PERMISSION_DENIED";
        } finally {
            try {
                outputStream.close();
                inputStream.close();
            } catch (Exception e) {
                return "PERMISSION_DENIED";
            }
        }
        return "SUCCESS";
    }

    public static String getAppPath(){
        return getContext().getFilesDir().getPath();
    }
    public static String getUSBPath(){
        String path = "";
        StorageManager mStorageManager = (StorageManager)getContext().getSystemService(Context.STORAGE_SERVICE);
        List<StorageVolume> volumes = mStorageManager.getStorageVolumes();
        try{
            Class<?> storageVolumeClazz = Class.forName("android.os.storage.StorageVolume");
            //通过反射调用系统hide的方法
            Method getPath = storageVolumeClazz.getMethod("getPath");
            Method isRemovable = storageVolumeClazz.getMethod("isRemovable");
            //    Method getUserLabel = storageVolumeClazz.getMethod("getUserLabel");//userLabel和description是一样的
            for (int i = 1; i < volumes.size(); i++) {
                StorageVolume storageVolume = volumes.get(i);//获取每个挂载的StorageVolume
                // 通过反射调用getPath、isRemovable、userLabel
                String storagePath = (String) getPath.invoke(storageVolume); //获取路径
                boolean isRemovableResult = (boolean) isRemovable.invoke(storageVolume);//是否可移除
                String description = storageVolume.getDescription(context);//此方法是android 7.0以上的
                ExtendsQtNative.printInfo("路径" + description + storagePath);
//                if (label.equals(description)){
//                    Log.e("getExternalPath--", " i=" + i + " ,storagePath=" + storagePath +  " ,description=" + description);
//                    path = storagePath;
//                    break;
//                }
//                if(description != "内部共享存储空间"){
//                    path += storagePath + ",";
//                }
                path += storagePath + ",";

            }
        }catch(Exception e){
            ExtendsQtNative.printInfo("获取USB路径出错");
        }
        return path;
    }

}
